<?php

namespace App\Models;

use App\Enums\BookStatus;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\File;
use Illuminate\Support\Str;

class Book extends Model
{
    use HasFactory;

    protected $casts = [
        'tag' => 'json',
        'status' => BookStatus::class,
    ];

    protected  static function booted()
    {
        static::updated(function ($model) {
        });
    }

    private function getBookBnString(): string
    {
        do {
            // 生成唯一的图书编号
            $bookNumber = substr(Str::uuid()->toString(),0,10);

            // 检查数据库中是否已存在相同的图书编号
            $exists = self::where('number', $bookNumber)->exists();

        } while ($exists);

        return $bookNumber;
    }

    public function category(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }



    public function borrowRecord()
    {
        return $this->hasMany(BorrowRecord::class, 'book_id', 'id');
    }

    public function chapters(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(Chapter::class, 'book_id', 'id');
    }

    public function defaultImg(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) => $this->getImg(),
        );
    }


    public function getImg(): array|string
    {
        // 指定目录路径
        $directory = public_path('images/swisnl/filament-backgrounds/curated-by-swis');

        // 获取目录中的所有文件
        $files = File::allFiles($directory);

        // 随机选择一个文件
        $randomFile = $files[rand(0, count($files) - 1)];

        // 获取文件的相对路径
        return str_replace(public_path(), '', $randomFile->getPathname());

    }
}
